import Vue from '../../node_modules/vue/dist/vue.js'
import Vuex from 'vuex'
var shopcar=JSON.parse(localStorage.getItem('shopcar')||'[]')
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
   shopcar:shopcar,
   c:0
  },
  mutations: {
    toshopcar(state,goodsinfo){
      var flag=false
      state.shopcar.some(item=>{
        if(item.id==goodsinfo.id){
          item.count+=parseInt(goodsinfo.count)
          flag=true
          return true
        }
      })
      if(!flag){
        state.shopcar.push(goodsinfo)
      }
      localStorage.setItem('shopcar',JSON.stringify(state.shopcar))
    },
    updateGoodsinfo(state,goodsinfo){
      //修改购物车中商品的数量
      state.shopcar.some(item=>{
        if(item.id==goodsinfo.id){
          item.count=parseInt(goodsinfo.count)
          return true
        }
      })
      //当修改完数量，把最新的数据保存到本地储存中
      localStorage.setItem('shopcar',JSON.stringify(state.shopcar))
    },
    reGoodsFrShopCar(state,id){
      state.shopcar.some((item,i)=>{
        if(item.id===id){
          state.shopcar.splice(i,1)
          return true
        }
      })
      localStorage.setItem('shopcar',JSON.stringify(state.shopcar))
    },
    updateGoodsSelected(state,info){
      state.shopcar.some(item=>{
        if(item.id===info.id){
          item.selected=info.selected
        }
      })
      localStorage.setItem('shopcar',JSON.stringify(state.shopcar))
    }
  },
  getters:{
    getallcount(state){
      var c=0;
      state.shopcar.forEach(item=>{
        c+=item.count;
        
      })
      return c
    },
    getGoodsCount(state){
      var co={};
      state.shopcar.forEach(item=>{
        co[item.id]=item.count
      });
      return co
    },
    getGoodsSelected(state){
      var s={};
      state.shopcar.forEach(item=>{
        s[item.id]=item.selected
      })
      return s
    },
    getCountAndAmount(state){
      var o={
        count:0,//勾选的总数
        amount:0 //勾选的总价
      }
      state.shopcar.some(item=>{
        if(item.selected===true){
          o.count+=item.count
          o.amount+=item.price*item.count
        }
      })
      return o
    }
  },
  actions: {
  },
  modules: {
  }
})
